using System;
using System.IO;
using HelloShared;

namespace HelloService
{
    public class FileTransfer : IFileTransfer
    {
        #region Public Methods

        public DateTime Heartbeat()
        {
            Console.WriteLine("{0:s} Telling the time", DateTime.Now);
            return DateTime.Now;
        }

        public void SendFieldUpdates(FieldEditMessage dataMessage)
        {
            Console.WriteLine("{0:s} Receiving package and saving to {1}", DateTime.Now, dataMessage.FileName);
            const string uploadFolder = @"..\..\UploadedFiles";
            var target = new DirectoryInfo(uploadFolder);
            string fileName = Path.Combine(target.FullName, dataMessage.FileName);
            FileStream targetStream;
            Stream sourceStream = dataMessage.UpdatePackage;

            try
            {
                using (targetStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    //read from the input stream in 4K chunks and save to output stream
                    const int bufferLen = 4096;
                    var buffer = new byte[bufferLen];
                    int count = 0;

                    while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                    }
                    targetStream.Close();
                    sourceStream.Close();
                }
            }
            catch (IOException ioEx)
            {
                Console.WriteLine(
                    "Could not read the file you sent. Check that your file is not bigger than the permitted transmission size (app.config)");
            }
        }

        #endregion
    }
}